package com.atgouwu.mall.common.exception;

import com.atgouwu.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

@Slf4j
@RestControllerAdvice //切面编程(有异常就走该切面),web的依赖
public class MyExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) { //统一异常处理
        log.error(e.getMessage(), e);
        return R.error(-1, e.getMessage());
    }

//    @ExceptionHandler(value = BadSqlGrammarException.class)
//    public R handleBadSqlGrammarException(BadSqlGrammarException e) { //指定异常类
//        log.error(e.getMessage(), e);
//        return R.error(-1, e.getMessage());
//    }

    @ExceptionHandler(value = MyException.class) //自定义异常类
    public R handleException(MyException e) {
        log.error(e.getMessage(), e);
        return R.error(-1, e.getMessage());
    }

    @ExceptionHandler({NoHandlerFoundException.class, //Controller类的上层异常:参数不合法,请求方式不对等(还没到自定义异常)
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            MethodArgumentNotValidException.class,
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class})
    public R handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(-1, e.getMessage());
    }
}
